package serverService;

import common.Message;
import common.MessageType;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author lhn
 * @date 2024-05-07 16:01
 */

public class ServerConnectClientThread extends Thread{
    private Socket socket;
    private String userId;
    public ServerConnectClientThread(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public void run() {
        //线程处于run状态，可以发送/接收消息
        super.run();
        while (true) {
            try {
                System.out.println("服务器和客户端"+ userId+"保持通讯，读取数据...");
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) objectInputStream.readObject(); //一直读取消息
                //根据message进行业务处理
                if (MessageType.MESSAGE_GET_ONLINE_FRIEND.equals(message.getMesType())) {
                    //拉取在线用户列表
                    System.out.println("用户" + message.getSender() + "获取在线用户列表");
                    String onlineUsers = ManageServerConnectClientThread.getOnlineUsers();
                    //封装message信息
                    Message message1 = new Message();
                    message1.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
                    message1.setContent(onlineUsers);
                    message1.setGetter(message.getSender());
                    //返回给客户端
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(message1);

                } else if (MessageType.MESSAGE_COMMON_MESSAGE.equals(message.getMesType())) {
                    //普通聊天功能
                    if (ManageServerConnectClientThread.checkUserOnline(message.getGetter())) {
                        //对方在线
                        ServerConnectClientThread serverConnectClientThread = ManageServerConnectClientThread.getServerConnectClientThread(
                                message.getGetter()
                        );
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                                serverConnectClientThread.getSocket().getOutputStream()
                        );
                        objectOutputStream.writeObject(message);
                    } else {
                        //TODO 保存到数据库实现离线留言
                        ManageServerConnectClientThread.addOfflineMsg(message.getGetter(), message);
                        System.out.println(message.getSendTime() + ":用户" + message.getSender() + "发送给" + message.getGetter() + "的离线留言(" + message.getContent() + ")已保存到数据库");
                    }


                } else if (MessageType.MESSAGE_COMMON_MESSAGE_ALL.equals(message.getMesType())) {
                    //用户向所有发送消息
                    System.out.println(message.getSendTime() + ": 用户(" + message.getSender() + ")对所有用户" + "说" + message.getContent());
                    HashMap<String, ServerConnectClientThread> hashMap = ManageServerConnectClientThread.getHashMap();
                    //遍历管理线程的集合,得到线程的socket,转发message
                    for (String key: hashMap.keySet()
                         ) {
                        if (!message.getSender().equals(key)) {
                            ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                                    hashMap.get(key).getSocket().getOutputStream()
                            );
                            objectOutputStream.writeObject(message);
                        }

                    }

                } else if (MessageType.MESSAGE_FILE_MESSAGE.equals(message.getMesType())) {
                    //用户向单个用户发送文件
                    if (ManageServerConnectClientThread.checkUserOnline(message.getGetter())) {
                        //接收文件的用户在线
                        System.out.println("用户" + message.getSender() + "向用户" + message.getGetter() + "发送文件");
                        ServerConnectClientThread serverConnectClientThread = ManageServerConnectClientThread.getServerConnectClientThread(message.getGetter());
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                        objectOutputStream.writeObject(message);
                    } else {
                        //TODO 保存到数据库实现离线文件
                        ManageServerConnectClientThread.addOfflineFile(message.getGetter(), message);
                        System.out.println(message.getSendTime() + ":用户" + message.getSender() + "发送给" + message.getGetter() + "的离线文件已保存到数据库");
                    }


                } else if (MessageType.MESSAGE_CLIENT_EXIT.equals(message.getMesType())) {
                    //客户端退出
                    System.out.println("用户 " + message.getSender() + " 退出系统");
                    ManageServerConnectClientThread.removeServerConnectClientThread(message.getSender());
                    socket.close();
                    break;  //退出循环

                } else {
                    System.out.println("暂不处理");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}